<template>
    <div class="container">
        <header>
            <h1>几何反转</h1>
        </header>

        <div class="game-board-container">
            <GameBoard3 :count="isGameOver" :message="isGameWon" @update-count="handleUpdateCount" @change="handleChange" />
        </div>

        <div class="game-info">
            <div class="score-container">
                得分: <span id="score">{{ gameStore.games.score }}</span>
            </div>
            <div class="score-container">
                剩余步数: <span id="steps">{{ gameStore.games.steps }}</span>
            </div>
            <div class="controls">
                <button @click="initGame()" :disabled="gameStore.games.isProcessing">重新开始</button>
            </div>
        </div>

        <div class="instructions">
            <h2>游戏规则</h2>
            <ul>
                <li>点击卡片会改变自身及上下左右相邻卡片的图案：黑桃 → 红心 → 方块 → 梅花</li>
                <li>当三个或更多相同图案在一条直线上（横向或纵向）时，它们会被消除</li>
                <li>四个横向相同图案会生成横向消除特殊卡片</li>
                <li>四个竖向相同图案会生成竖向消除特殊卡片</li>
                <li>五个同行/同列图案会生成万能Joker卡片</li>
                <li>T型或L型图案会生成爆破特殊卡片</li>
                <li>消除后上方的卡片会下落，顶部会补充新的卡片</li>
                <li>每次消除获得10分，连续消除获得额外加分</li>
                <li>在规定的步数内，尽可能多地消除卡片来获得高分！</li>
            </ul>
        </div>

    </div>
    <GameOver v-if="isGameOver" :score="gameStore.games.score" @retry="startNewGame" @main-menu="returnToMenu" />
        <!-- 胜利界面 -->
    <Victory 
      v-if="isGameWon"
      :score="gameStore.games.score"
      @retry="startNewGame"
      @main-menu="returnToMenu"
    />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import GameBoard3 from '@/components/GameBoard3.vue'
import { useGameStore } from '@/store/game'
import GameOver from '@/views/Fail.vue'
import router from '@/router';
import Victory from '@/views/Victory.vue';

let isGameWon = ref(false)
let isGameOver = ref(false)
const SIZE = 8;
const gameStore = useGameStore();
// 处理子组件传递的更新值
const handleUpdateCount = (newCount) => {
  isGameOver.value = newCount;
};
const handleChange = (newCount) => {
    isGameWon.value = newCount;
}
// 刷新游戏逻辑
function startNewGame() {
  initGame();
  isGameOver.value = false;
}
const initGame = () => {
    const gameStore = useGameStore();
    gameStore.games.board = []
    gameStore.games.score = 0
    gameStore.games.comboCount = 0
    gameStore.games.isProcessing = true
    gameStore.games.size = SIZE
    gameStore.games.effectChainDepth = 0
    gameStore.games.steps = 10
    // 初始化棋盘 - 确保没有初始匹配
    const newBoard = [];
    const suits = ['spade', 'heart', 'diamond', 'club'];

        for (let row = 0; row < SIZE; row++) {
        newBoard[row] = [];
        for (let col = 0; col < SIZE; col++) {
            const suit = generateSuitWithCheck(newBoard, row, col, suits);
            newBoard[row][col] = {
                suit: suit,
                row: row,
                col: col,
                isChanging: false,
                isHighlighted: false,
                isMatched: false,
                specialType: 'none',
                isAble: true
            };
        }
    }

        // 检查并消除所有初始匹配
    eliminateInitialMatches(newBoard, suits);
    gameStore.games.board = newBoard;

    // 设置一个短暂的延迟后允许操作
    setTimeout(() => {
        gameStore.games.isProcessing = false;
    }, 500);
    const a = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7],
    [0, 7], [1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1], [7, 0]]
    a.forEach(info => {
        gameStore.games.board[info[0]][info[1]].isAble = false
        gameStore.games.board[info[0]][info[1]].specialType = 'locked'
    })
};
// 生成卡片的逻辑，确保不会与相邻两个相同
function generateSuitWithCheck(board, row, col, suits) {
    if (row > 1 && board[row - 1] && board[row - 1][col] && board[row - 2] && board[row - 2][col]) {
        // 避免垂直匹配
        const prevSuit1 = board[row - 1][col].suit;
        const prevSuit2 = board[row - 2][col].suit;
        const availableSuits = suits.filter(s => s !== prevSuit1 && s !== prevSuit2);
        return availableSuits.length > 0
            ? availableSuits[Math.floor(Math.random() * availableSuits.length)]
            : suits[Math.floor(Math.random() * suits.length)];
    } else if (col > 1 && board[row][col - 1] && board[row][col - 2]) {
        // 避免水平匹配
        const prevSuit1 = board[row][col - 1].suit;
        const prevSuit2 = board[row][col - 2].suit;
        const availableSuits = suits.filter(s => s !== prevSuit1 && s !== prevSuit2);
        return availableSuits.length > 0
            ? availableSuits[Math.floor(Math.random() * availableSuits.length)]
            : suits[Math.floor(Math.random() * suits.length)];
    } else {
        // 默认随机选择
        return suits[Math.floor(Math.random() * suits.length)];
    }
}

// 检查并消除所有初始匹配
function eliminateInitialMatches(board, suits) {
    let hasMatch = true;
    while (hasMatch) {
        hasMatch = false;
        const matches = [];

        // 找出所有水平匹配
        for (let row = 0; row < SIZE; row++) {
            for (let col = 0; col < SIZE - 2; col++) {
                if (
                    board[row][col].suit === board[row][col + 1].suit &&
                    board[row][col].suit === board[row][col + 2].suit
                ) {
                    matches.push({ row, col, direction: 'horizontal' });
                    hasMatch = true;
                }
            }
        }

        // 找出所有垂直匹配
        for (let col = 0; col < SIZE; col++) {
            for (let row = 0; row < SIZE - 2; row++) {
                if (
                    board[row][col].suit === board[row + 1][col].suit &&
                    board[row][col].suit === board[row + 2][col].suit
                ) {
                    matches.push({ row, col, direction: 'vertical' });
                    hasMatch = true;
                }
            }
        }

        // 重新生成匹配的卡片
        for (const match of matches) {
            if (match.direction === 'horizontal') {
                // 重新生成中间的卡片
                board[match.row][match.col + 1].suit = generateSuitWithCheck(board, match.row, match.col + 1, suits);
            } else if (match.direction === 'vertical') {
                // 重新生成中间的卡片
                board[match.row + 1][match.col].suit = generateSuitWithCheck(board, match.row + 1, match.col, suits);
            }
        }
    }
}
onMounted(() => {
    initGame();
})
function returnToMenu() {
    router.push('/')
}
setTimeout(() => {
    if (gameStore.games.steps <= 0) {
        isGameOver.value = true
    }
}, 500);
</script>

<style scoped>
.container {
    display: grid;
    grid-template-areas:
        "header header"
        "game info"
        "instructions instructions";
    grid-template-columns: 1fr 300px;
    grid-template-rows: auto 1fr auto;
    gap: 20px;
    max-width: 900px;
    margin: 20px auto;
    padding: 20px;
    background: #fff;
    border-radius: 15px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

header {
    grid-area: header;
    text-align: center;
    padding: 15px;
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    margin-bottom: 0;
}

.game-info {
    grid-area: info;
    display: flex;
    flex-direction: column;
    gap: 15px;
    background: rgba(0, 0, 0, 0.03);
    padding: 15px;
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.1);
}

.game-board-container {
    grid-area: game;
    background: rgba(0, 0, 0, 0.03);
    padding: 15px;
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
}

.instructions {
    grid-area: instructions;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    margin-top: 0;
}

h1 {
    font-size: 2.8rem;
    margin-bottom: 10px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
    background: linear-gradient(45deg, #ff9a9e, #fad0c4, #a1c4fd);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.score-container,
.controls {
    background: rgba(0, 0, 0, 0.3);
    padding: 12px 25px;
    border-radius: 10px;
    font-size: 1.2rem;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    color: white;
}

#score {
    font-weight: bold;
    font-size: 1.4rem;
    color: #FFD700;
}

button {
    background: linear-gradient(45deg, #ff9a9e, #fad0c4);
    border: none;
    padding: 10px 20px;
    border-radius: 50px;
    color: #333;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

button:hover:not(:disabled) {
    transform: translateY(-3px);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.instructions h2 {
    margin-bottom: 12px;
    color: #FFD700;
    text-align: center;
}

.instructions ul {
    list-style-type: none;
    padding: 0 15px;
    text-align: left;
}

.instructions li {
    margin-bottom: 10px;
    padding-left: 25px;
    position: relative;
    line-height: 1.5;
}

.instructions li:before {
    content: "◆";
    position: absolute;
    left: 0;
    color: #FFD700;
}
</style>